package main

import (
	"context"
	"embed"
	"fmt"
	"html/template"
	"io/ioutil"
	"net/http"
	"net/url"

	"github.com/gin-gonic/gin"
	lark "github.com/larksuite/oapi-sdk-go/v3"
	larkauthen "github.com/larksuite/oapi-sdk-go/v3/service/authen/v1"
)

var (
	//go:embed template/*
	templateFS embed.FS
	//go:embed asset/*
	assetFS    embed.FS
	ID, Secret = "cli_a4bd333241bcd00d", "rqme26ZkBATmTODRjEfNOgPUUwKPjAHT"
	APPID      = "c9b6b1cc-8117-4258-a6a5-dec42152029f"
)

func main() {
	app := gin.Default()
	app.Any("/asset/*filepath", func(c *gin.Context) {
		staticServer := http.FileServer(http.FS(assetFS))
		staticServer.ServeHTTP(c.Writer, c.Request)
	})
	app.SetHTMLTemplate(template.Must(template.New("").ParseFS(templateFS, "template/*")))
	app.Handle("GET", "/", index)
	app.Handle("GET", "/callback", callback)
	app.GET("/get_appid", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"appid": ID,
		})
	})
	gin.SetMode(gin.ReleaseMode)
	app.Run(":8080")
}

func index(c *gin.Context) {
	c.HTML(http.StatusOK, "index.tmpl", gin.H{
		"title": "验证用户信息",
	})
}

func callback(c *gin.Context) {
	code := c.Query("code")
	// 创建 Client
	client := lark.NewClient(ID, Secret)
	// 创建请求对象
	req := larkauthen.NewCreateAccessTokenReqBuilder().
		Body(larkauthen.NewCreateAccessTokenReqBodyBuilder().
			GrantType("authorization_code").
			Code(code).
			Build()).
		Build()
	// 发起请求
	resp, _ := client.Authen.AccessToken.Create(context.Background(), req)
	// 业务处理
	oaurl := "http://newoa.houde-food.com/ssologin/getToken"
	data := url.Values{}
	data.Set("appid", "c9b6b1cc-8117-4258-a6a5-dec42152029f")
	data.Set("loginid", *resp.Data.Name)
	oadata, _ := http.PostForm(oaurl, data)
	token, _ := ioutil.ReadAll(oadata.Body)
	fmt.Println(string(token))
	c.JSON(http.StatusOK, gin.H{
		"address": fmt.Sprintf("http://newoa.houde-food.com/wui/index.html?ssoToken=%s#/main", string(token)),
	})
}
